package com.wulian.common.interceptor;


import com.wulian.common.constants.CommonConstants;
import com.wulian.common.context.BaseContextHandler;
import com.wulian.common.suport.RibbonFilterContext;
import com.wulian.common.suport.RibbonFilterContextHolder;
import com.wulian.common.util.JSONUtil;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author zc
 */
@Configuration
public class UserInfoRequestInterceptor implements RequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoRequestInterceptor.class);

    public UserInfoRequestInterceptor() {
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {

        String json = JSONUtil.toJSON(BaseContextHandler.getUserInfo());
        if ((StringUtils.isBlank(json))||("null".equals(json))) {
            RibbonFilterContext context = RibbonFilterContextHolder.getCurrentContext();
            json = context.get("userInfo");
        }
        try {
            if(StringUtils.isNotBlank(json)){
                json = URLEncoder.encode(json, "UTF-8");
            }
        } catch (UnsupportedEncodingException var4) {
            logger.error("json编码异常 {}", var4.getMessage());
        }
        requestTemplate.header(CommonConstants.USER_INFO, json);
    }
}
